package queue;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * 借款方
 * @author：涂有
 * @date 2017年2月18日 下午10:06:09
 */
public class QBorrower {

	private QueueConnection connection;
	private QueueSession session;
	private Queue responseQueue;
	private Queue requestQueue;
	
	public QBorrower(String queueConnectionFactory, String requestQueue, String responseQueue) throws NamingException, JMSException{
		
		Context context = new InitialContext();
		QueueConnectionFactory qcf = (QueueConnectionFactory)context.lookup(queueConnectionFactory);
		connection = qcf.createQueueConnection();
		connection.start();
		
		session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
		
		this.responseQueue = (Queue)context.lookup(responseQueue);
		this.requestQueue = (Queue)context.lookup(requestQueue);
	}
	
	private void sendLoanRequest(double salary, double loanAmount) throws JMSException{
		
		MapMessage mapMessage = session.createMapMessage();
		mapMessage.setDouble("Salary", salary);
		mapMessage.setDouble("LoanAmount", loanAmount);
		mapMessage.setJMSReplyTo(responseQueue);
		
		QueueSender sender = session.createSender(requestQueue);
		sender.send(mapMessage);
		
		String filter = "JMSCorrelationID = '" + mapMessage.getJMSMessageID() + "'";
		QueueReceiver queueReceiver = session.createReceiver(responseQueue, filter);
		TextMessage textMessage = (TextMessage)queueReceiver.receive(30000);
		if(textMessage == null){
			
			System.out.println("QLender not reponseding");
		}else{
			
			System.out.println("Loan request was " + textMessage.getText());
		}
	}
	
	private void exit() throws JMSException{
		
		connection.close();
	}
	
	public static void main(String[] args) throws NamingException, JMSException, IOException {
		
		QBorrower borrower = new QBorrower("a", "b", "c");
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("欢迎申请：");
		while(true){
			
			System.out.print(">");
			String line = reader.readLine();
			if(line == null || "".equals(line.trim())){
				
				borrower.exit();
				System.exit(0);
			}else{
				
				StringTokenizer tokenizer = new StringTokenizer(line, ",");
				double salary = Double.valueOf(tokenizer.nextToken()).doubleValue();
				double loanAmount = Double.valueOf(tokenizer.nextToken()).doubleValue();
				borrower.sendLoanRequest(salary, loanAmount);
			}
		}
	}
}
